package com.kl;

import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.client.indices.GetIndexResponse;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;

/**
 * 索引 等同于 MySQL中的数据库
 */
public class ES_Index {

    private RestHighLevelClient client;

    // 客户端连接
    @Before
    public void initClint() {
        client = new RestHighLevelClient
                (RestClient.builder(new HttpHost("localhost", 9200, "http")));
    }

    // 关闭连接
    @After
    public void close() throws IOException {
        client.close();
    }

    // 创建索引
    @Test
    public void createIndex() throws IOException {
        // 定义索引--请求对象
        CreateIndexRequest request = new CreateIndexRequest("user");
        // 发送请求---创建索引---返回响应
        CreateIndexResponse response = client.indices().create(request,
                RequestOptions.DEFAULT);
        boolean acknowledged = response.isAcknowledged();
        // 响应状态
        System.out.println("操作状态 = " + acknowledged);
    }

    // 查询索引
    @Test
    public void queryIndex() throws IOException {
        // 查询索引 - 请求对象
        GetIndexRequest request = new GetIndexRequest("user");
        // 发送请求，获取响应
        GetIndexResponse response = client.indices().get(request,
                RequestOptions.DEFAULT);

        System.out.println("aliases:" + response.getAliases());
        System.out.println("mappings:" + response.getMappings());
        System.out.println("settings:" + response.getSettings());
    }

    // 删除索引
    @Test
    public void test() throws IOException {
        // 删除索引 - 请求对象
        DeleteIndexRequest request = new DeleteIndexRequest("user");
        // 发送请求，获取响应
        AcknowledgedResponse response = client.indices().delete(request, RequestOptions.DEFAULT);
        // 操作结果
        System.out.println("操作结果 ： " + response.isAcknowledged());
    }
}
